package cc.vv.baselibrary.util

import android.content.Context
import java.lang.ref.WeakReference


/**
 *
 * @author Zml
 * @date 2018/7/26.
 */
abstract class BasePresenter<M, V> {

    var mModel: M? = null

    var mView: V? = null

    var mContext: Context? = null

    var mViewRef: WeakReference<V>? = null
    /**
     * presenter绑定,持有view 的接口
     *
     * @param v
     */
    fun attach(model: M, v: V) {
        this.mViewRef = WeakReference<V>(v)
        this.mModel = model
    }

    /**
     * presenter释放持有view层的接口,防止内存泄漏
     */
    fun detach() {
        if (null != mViewRef) {
            this.mViewRef!!.clear()
            this.mViewRef = null
        }
    }

    fun getContext(context: Context) {
        mContext = context
    }

    fun getView(): V? {
        return if (isAttach()) {
            mViewRef!!.get()
        } else {
            null
        }
    }

    private fun isAttach(): Boolean {
        return null != mViewRef && null != mViewRef!!.get()
    }
}